package org.gnyxy.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.gnyxy.constant.DeleteConstant;
import org.gnyxy.constant.MessageConstant;
import org.gnyxy.context.BaseContext;
import org.gnyxy.dto.UserLoginDTO;
import org.gnyxy.entity.User;
import org.gnyxy.exception.BaseException;
import org.gnyxy.exception.LoginFailedException;
import org.gnyxy.mapper.UserMapper;
import org.gnyxy.properties.WeChatProperties;
import org.gnyxy.service.UserService;
import org.gnyxy.utils.HttpClientUtil;
import org.gnyxy.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String openId = getOpenId(userLoginDTO.getCode());

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.getByOpenId(openId);

        if (user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .deleted(DeleteConstant.IS_NOT_DELETED)
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    /**
     * 更新个人资料
     * @param user
     */
    @Override
    public void update(User user) {
        if (user == null){
            throw new BaseException(MessageConstant.OBJECT_IS_NULL);
        }
        user.setId(BaseContext.getCurrentId());
        userMapper.update(user);
    }

    /**
     * 根据id查询用户资料
     * @param id
     * @return
     */
    @Override
    public UserVO getById(Long id) {
        if (id == null){
            throw new BaseException(MessageConstant.ID_IS_NULL);
        }
        User user = userMapper.getById(id);
        if (user == null) throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }

    /**
     * 获取openid方法
     * @param code
     * @return
     */
    private String getOpenId(String code){
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
